<template>
  <div>
    <div style="width:500px;margin: 100px auto;text-align:center;">
      <el-form ref="registerForm" :model="registerDto" :rules="RegisterDto_Rules" label-width="100px">
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="registerDto.phoneNumber" placeholder="请输入手机号码" name="phoneNumber" type="text" auto-complete="on" />
        </el-form-item>
        <el-form-item label="手机验证码" prop="code">
          <el-input v-model.trim="registerDto.code" class="verifycode_input" type="text" :placeholder="$t('rules.verifyCode')">
            <el-button v-if="!isSendMsg" slot="append" @click="sendPhoneNum">
              <span>{{ $t('register.sendMSG') }}</span>
            </el-button>
            <el-button v-else slot="append" class="noClick">
              <span>{{ reSendTime }}(s)</span>
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input ref="password" v-model="registerDto.password" type="password" :placeholder="$t('rules.passWord')" name="password" auto-complete="on" />
        </el-form-item>
      </el-form>
      <el-button @click="routerRedirect('/')">上一步</el-button>
      <el-button type="primary" :loading="loading" @click="submitRegister">立即注册</el-button>
    </div>
  </div>
</template>
<script>
// import { mapState, mapActions } from 'vuex';
import { RegisterDto_Rules } from '@/lib/validate/register/index.js';
import { RegisterUserInput } from '@/lib/form/swaggerForm.js';
import {
  api_POST_UsersRegisterSmsCode,
  api_POST_UsersRegister
} from '@/extend/api/swaggerApi/identity';
export default {
  data() {
    return {
      RegisterDto_Rules: new RegisterDto_Rules(),
      registerDto: new RegisterUserInput(),
      loading: false,
      isSendMsg: false, // 是否已经发送验证码
      reSendTime: 0 // 验证码倒计时
    };
  },
  methods: {
    routerRedirect(path) {
      this.$router.push({
        path: path
      });
    },
    // 发送手机验证码
    sendPhoneNum() {
      // 校验phoneNumber的值是否有效
      this.$refs.registerForm.validateField('phoneNumber', phoneError => {
        if (!phoneError) {
          // phoneNumber手机号码本地校验已通过
          api_POST_UsersRegisterSmsCode({
            phoneNumber: this.registerDto.phoneNumber,
            isNew: true
          }).then(res => {
            if (res.result === 'Success') {
              this.$message({ type: 'success', message: '手机验证码已发送' });
            } else if (res.result === 'AlreadyExists') {
              this.$message({ type: 'warning', message: '用户已经存在' });
            } else if (res.result === 'InvalidVerificationCode') {
              this.$message({ type: 'warning', message: '无效的验证码' });
            }
          });
          // 同时执行倒计时
          this.countDownTime(60);
        } else {
          return false;
        }
      });
    },
    // 短信倒计时
    countDownTime(num) {
      let timer = null;
      clearInterval(timer);
      this.isSendMsg = true;
      this.reSendTime = num;
      timer = setInterval(() => {
        this.isSendMsg = true;
        this.reSendTime -= 1;
        if (this.reSendTime <= 0) {
          clearInterval(timer);
          this.isSendMsg = false;
        }
      }, 1000);
    },
    // 提交 —— 注册
    submitRegister() {
      this.$refs['registerForm'].validate(valid => {
        if (valid) {
          this.loading = true;
          api_POST_UsersRegister(this.registerDto)
            .then(res => {
              this.loading = false;
              if (res.result === 'Success') {
                this.$message({ message: '注册成功！', type: 'success' });
                this.$router.push({
                  path: '/chooseType'
                });
              } else if (res.result === 'AlreadyExists') {
                this.$message({ type: 'warning', message: '用户已经存在' });
              } else if (res.result === 'InvalidVerificationCode') {
                this.$message({ type: 'warning', message: '无效的验证码' });
              }
            })
            .catch(() => {
              this.loading = false;
              this.$message({ type: 'warning', message: error });
            });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
